package com.example.demo.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpClientProxy {


    /**
     * 将参数封装成 HttpEntity
     *
     * @param params
     * @return
     */
    private static HttpEntity transMap2HttpEntity(Map<String, String> params) {
        List<NameValuePair> naps = new ArrayList<NameValuePair>();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                naps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        EntityBuilder builder = EntityBuilder.create();
        builder.setParameters(naps);
        return new UrlEncodedFormEntity(naps, Consts.UTF_8);
    }

    /**
     * 发送HTTP的POST请求
     *
     * @param requestUrl
     * @param requestContent
     * @return
     * @throws IOException
     */
    public static String post(String requestUrl, String requestContent) throws Exception {
        StringEntity requestEntity = new StringEntity(requestContent);
        return post(requestUrl, requestEntity);
    }

    /**
     * 发送HTTP的POST请求
     *
     * @param requestUrl
     * @param params
     * @return
     * @throws IOException
     */
    public static String post(String requestUrl, Map<String, String> params) throws Exception {
        return post(requestUrl, transMap2HttpEntity(params));
    }


    /**
     * 发送HTTP的POST请求
     *
     * @param requestUrl
     * @param httpEntity
     * @return
     * @throws IOException
     */
    private static String post(String requestUrl, HttpEntity httpEntity) throws Exception {
        HttpPost httpPost = new HttpPost(requestUrl);
        httpPost.setEntity(httpEntity);
        try {
            log.info("发起请求的地址:" + httpPost.getRequestLine());
            log.info("发起请求的格式:" + httpEntity.getContentType().toString());
            CloseableHttpResponse httpResponse = HttpClientUtils.getHttpClient().execute(httpPost);
            log.info("----------------------------------------");
            // 打印响应状态
            log.info(httpResponse.getStatusLine().toString());
            return processResponse(httpResponse);
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 发送HTTP的GET请求
     *
     * @param requestUrl
     * @param params
     * @return
     * @throws IOException
     */
    public static String get(String requestUrl, String params) throws IOException {
        HttpGet HttpGet = new HttpGet(requestUrl + params);
        CloseableHttpResponse httpResponse = HttpClientUtils.getHttpClient().execute(HttpGet);
        return processResponse(httpResponse);
    }

    /**
     * 发送HTTP的GET请求
     *
     * @param requestUrl
     * @param params
     * @return
     * @throws IOException
     */
    public static String get(String requestUrl, Map<String, String> params) throws IOException {
        StringBuilder stab = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            stab.append("&").append(entry.getKey()).append("=").append(entry.getValue());
        }
        HttpGet HttpGet = new HttpGet(requestUrl + stab.toString());
        CloseableHttpResponse httpResponse = HttpClientUtils.getHttpClient().execute(HttpGet);
        return processResponse(httpResponse);
    }

    /**
     * 处理响应信息
     *
     * @param httpResponse
     * @return
     * @throws IOException
     */
    private static String processResponse(CloseableHttpResponse httpResponse) throws IOException {
        String result = null;
        try {
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, "UTF-8");
                // 打印响应内容
                if (StringUtils.isNotBlank(result)) {
                    if (isJson(result)) {
                        JSONObject json = JSONObject.parseObject(result);
                        result = json.toString();
                    }
                    log.info("Response=" + result);
                } else {
                    log.info("Response=" + result);
                }
            }
            EntityUtils.consume(resEntity);
            return result;
        } finally {
            if (null != httpResponse) {
                httpResponse.close();
            }
        }
    }

    /**
     * 判断是否为字符串
     *
     * @param content
     * @return
     */
    public static boolean isJson(String content) {
        try {
            JSONObject jsonStr = JSONObject.parseObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
